import 'package:flutter/material.dart';
import 'package:flutter_sample/tab/ui/home/article/category_articles_viewmodel.dart';
import 'package:provider/provider.dart';
import 'ui_articles.dart';

class CategoryArticlesUI extends StatefulWidget {
  const CategoryArticlesUI({
    Key? key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ArticleCategoryState();
}

class _ArticleCategoryState extends State<CategoryArticlesUI>
    with TickerProviderStateMixin {

  @override
  void initState() {
    super.initState();
    // initState中刷新ViewModel的一种方式
    Provider.of<CategoryArticlesViewModel>(context, listen: false)
        .requestCategories();
  }

  List<Widget> _buildTabs(CategoryArticlesViewModel viewModel) {
    return viewModel.categories
        .map((e) => Tab(
              text: e.name,
              iconMargin: const EdgeInsets.all(0.0),
            ))
        .toList();
  }

  List<Widget> _buildContentWidgets(CategoryArticlesViewModel viewModel) {
    return viewModel.categories
        .map((category) => UIArticles(category: category.name))
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    ThemeData themeData = Theme.of(context);
    CategoryArticlesViewModel viewModel =
    Provider.of<CategoryArticlesViewModel>(context);
    TabController tabController =
    TabController(vsync: this, length: viewModel.categories.length);
    return Column(
      mainAxisSize: MainAxisSize.max,
      children: [
        TabBar(
          isScrollable: true,
          unselectedLabelColor: Colors.grey,
          labelColor: themeData.primaryColor,
          labelStyle: const TextStyle(
            fontSize: 16,
          ),
          tabs: _buildTabs(viewModel),
          controller: tabController,
        ),
        Expanded(
          child: TabBarView(
            controller: tabController,
            children: _buildContentWidgets(viewModel),
          ),
        ),
      ],
    );
  }
}
